package com.haitai.solr.utils;

import com.haitai.solr.resp.Pager;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class SolrOprUtils {

    private static Logger logger = LoggerFactory.getLogger(SolrOprUtils.class);

    /**
     * 向solr服务器添加数据信息
     *
     * @param url
     * @param map
     * @return
     */
    public static boolean addInfoToSolr(String url, TreeMap<String, Object> map) {
        HttpSolrClient solrClient = new HttpSolrClient.Builder(url).build();
        SolrInputDocument document = new SolrInputDocument();

        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            document.setField(entry.getKey(), entry.getValue());
        }

        try {
            UpdateResponse resp = solrClient.add(document);
            logger.info("solr添加数据返回status为：{}", resp.getStatus());
            solrClient.commit();
            return resp.getStatus() == 0;
        } catch (Exception e) {
            logger.error("索引添加失败", e);
        } finally {
            document.clear();
            try {
                solrClient.close();
            } catch (Exception e) {
                logger.error("solrClient关闭异常", e);
            }
        }
        return false;
    }

    /**
     * 更新操作和添加一样，只是id不同而已,建议先删后加更新后的数据
     * @param url
     * @param map
     * @return
     */
    public static boolean updateInfoToSolr(String url, TreeMap<String, Object> map) {
        HttpSolrClient solrClient = new HttpSolrClient.Builder(url).build();
        SolrInputDocument document = new SolrInputDocument();

        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            document.setField(entry.getKey(), entry.getValue());
        }

        try {
            UpdateResponse resp = solrClient.add(document);
            logger.info("solr更新数据返回status为：{}", resp.getStatus());
            solrClient.commit();
            return resp.getStatus() == 0;
        } catch (Exception e) {
            logger.error("索引更新失败", e);
        } finally {
            document.clear();
            try {
                solrClient.close();
            } catch (Exception e) {
                logger.error("solrClient关闭异常", e);
            }
        }
        return false;
    }

    /**
     * 根据指定的key/value 参数删除数据
     * @param delUrl solr服务地址
     * @param key
     * @param value
     * @return
     */
    public static boolean delByParam(String delUrl, String key, String value) {
        HttpSolrClient solrClient = new HttpSolrClient.Builder(delUrl).build();
        String queryStr = key + ":" + value;
        try {
            UpdateResponse resp = solrClient.deleteByQuery(queryStr);
            logger.info("solr删除数据返回status为：{}", resp.getStatus());
            solrClient.commit();
            return resp.getStatus() == 0;
        } catch (Exception e) {
            logger.error("删除失败", e);
        } finally {
            try {
                solrClient.close();
            } catch (Exception e) {
                logger.error("solrClient关闭异常", e);
            }
        }
        return false;
    }

    /***
     * 查询
     * @param queryUrl  solr地址及核心服务
     * @param queryData 查询条件   类似  id:*
     * @param outPutItem 需要返回的字段，用 , 隔开。
     * @param pager 分页
     * @return
     */
    public static Pager queryPageData(String queryUrl, String queryData, String outPutItem, Pager pager) {
        HttpSolrClient solrClient = new HttpSolrClient.Builder(queryUrl).build();
        SolrQuery query = new SolrQuery();
        //设定查询字段 queryData 类似  id:* or content:ddd  and age:12
        query.set("q", queryData);
        //默认域
//      query.set("df", "dfilecontext");

        //指定返回结果字段
        query.setIncludeScore(true);

        //分页开始  从多少条数据开始按每页数量取值
        int start = (pager.getCurrentPage() - 1) * pager.getPageSize();
        query.setStart(start);
        //设定返回记录数，默认为10条
        query.setRows(pager.getPageSize());

        query.setSort("id", SolrQuery.ORDER.asc);

        //只查询指定域
//        query.set("fl", "id,product_title,product_price");
        query.set("fl", outPutItem);

        try {
            QueryResponse response = solrClient.query(query);
            //5.提取结果
            SolrDocumentList documents = response.getResults();
            //查询到的条数
            long totalNum = documents.getNumFound();
            pager = new Pager(pager.getPageSize(), (int) totalNum, pager.getCurrentPage());

            List<Map<String, Object>> list = new ArrayList<>();
            for (SolrDocument doc : documents) {
                Map<String, Object> data = new TreeMap<>();
                Iterator<Map.Entry<String, Object>> it = doc.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    data.put(entry.getKey(), entry.getValue());
                }
                list.add(data);
            }
            pager.setData(list);
            return pager;
        } catch (Exception e) {
            logger.info("solr查询异常", e);
        } finally {
            try {
                solrClient.close();
            } catch (Exception e) {
                logger.error("solrClient关闭异常", e);
            }
        }
        return pager;
    }

    /**
     * 修改数据
     * @param url
     * @param map
     * @return
     */
    public boolean updateSolrData(String url, TreeMap<String, Object> map){
        HttpSolrClient solrClient = new HttpSolrClient.Builder(url).build();


        return false;
    }

}
